package ysq.xyg.controller;


import com.alibaba.fastjson.JSONArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import ysq.xyg.model.BaseMenu;
import ysq.xyg.model.Member;
import ysq.xyg.model.Product;
import ysq.xyg.model.info.BaseUserInfo;
import ysq.xyg.model.info.UserInfo;
import ysq.xyg.service.BaseDepartMenuService;
import ysq.xyg.service.BaseMenuService;
import ysq.xyg.service.MemberService;
import ysq.xyg.service.ProductService;
import ysq.xyg.util.BaseConstant;
import ysq.xyg.util.DateUtil;
import ysq.xyg.util.ProProperties;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author yu sheng qiang
 * @create 2017-03-22 11:57
 **/
@Controller
public class CommonController extends BaseController{
    private static Logger log= LoggerFactory.getLogger(CommonController.class);
    @Resource
    private BaseMenuService baseMenuService;
    @Resource
    private MemberService memberService;
    @Resource
    private ProductService productService;

    /**
     * 验证页面
     * */
    @RequestMapping(value="/{id}.txt")
    public void checkTxt(HttpServletRequest request, HttpServletResponse response, @PathVariable String id){
        String realPath = request.getSession().getServletContext().getRealPath("/mobile/img/");
        OutputStream outputStream = null;
        FileInputStream inputStream = null;
        try {
            outputStream = response.getOutputStream();
            String absoluteAdress = realPath + "/"+id+".txt";
            inputStream = new FileInputStream(absoluteAdress);
            byte[] buffer=new byte[1024];
            int len=-1;
            StringBuffer sb=new StringBuffer();
            while ((len=inputStream.read(buffer))!=-1){
                outputStream.write(buffer,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
                if (inputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 注册页面
     * */
    @RequestMapping(value="/register")
    public ModelAndView register(HttpServletRequest request,HttpServletResponse response){

        return new ModelAndView("/register");
    }

    /**
     * 管理员登录页面
     * */
    @RequestMapping(value="/managerLogin")
    public ModelAndView managerLogin(HttpServletRequest request,HttpServletResponse response){
        BaseUserInfo baseUserInfo=new BaseUserInfo();
        baseUserInfo.setUserid(BaseController.CookiesAcceptObject(request,BaseConstant.COOKIE_LOGINNAME));
        baseUserInfo.setUserpassword(BaseController.CookiesAcceptObject(request,BaseConstant.COOKIE_PASSWORD));
        if(baseUserInfo.getUserid()!=null && !"".equals(baseUserInfo.getUserid()) && baseUserInfo.getUserpassword()!=null && !"".equals(baseUserInfo.getUserpassword())){
            baseUserInfo.setAutoLogin(2);
        }else{
            baseUserInfo.setAutoLogin(1);
        }
        log.info("baseUserInfo-"+baseUserInfo.toString());
        return new ModelAndView("/login").addObject(baseUserInfo);
    }
    /**
     * 用户登录页面
     * */
    @RequestMapping(value="/userLogin")
    public ModelAndView userLogin(HttpServletRequest request,HttpServletResponse response){
        UserInfo userInfo=new UserInfo();
        userInfo.setUserName(BaseController.CookiesAcceptObject(request,BaseConstant.USER_COOKIE_LOGINNAME));
        userInfo.setUserPassword(BaseController.CookiesAcceptObject(request,BaseConstant.USER_COOKIE_PASSWORD));
        if(userInfo.getUserName()!=null && !"".equals(userInfo.getUserName()) && userInfo.getUserPassword()!=null && !"".equals(userInfo.getUserPassword())){
            userInfo.setAutoLogin(2);
        }else{
            userInfo.setAutoLogin(1);
        }
        log.info("userInfo-"+userInfo.toString());
        return new ModelAndView("/pcLogin").addObject(userInfo);
    }

    /**
     * 登录页面（默认是首页）
     * */
    @RequestMapping(value="/")
    public ModelAndView index(HttpServletRequest request,HttpServletResponse response){
        BaseUserInfo baseUserInfo=new BaseUserInfo();
        baseUserInfo.setUserid(BaseController.CookiesAcceptObject(request,BaseConstant.COOKIE_LOGINNAME));
        baseUserInfo.setUserpassword(BaseController.CookiesAcceptObject(request,BaseConstant.COOKIE_PASSWORD));
        if(baseUserInfo.getUserid()!=null && !"".equals(baseUserInfo.getUserid()) && baseUserInfo.getUserpassword()!=null && !"".equals(baseUserInfo.getUserpassword())){
            baseUserInfo.setAutoLogin(2);
        }else{
            baseUserInfo.setAutoLogin(1);
        }
        log.info("baseUserInfo-"+baseUserInfo.toString());
        //return new ModelAndView("/login").addObject(baseUserInfo);
        return new ModelAndView("/pcIndex").addObject(baseUserInfo);
    }
    /**
     * 登录进入默认页面
     * */
    @RequestMapping(value="/main")
    public ModelAndView main(HttpServletRequest request,HttpServletResponse response){
        BaseUserInfo baseUserInfo=acceptCurrentUser(request);
        Date newDate=new Date();
        List<String> dataList=new ArrayList<String>();
        List<Integer> memberList=new ArrayList<Integer>();
        List<Integer> productList=new ArrayList<Integer>();
        Integer currentAllMember=memberService.selectMemberCount(new Member());
        Product product=new Product();
        product.setStartDate(DateUtil.DateToStr(newDate,DateUtil.DATE_YEARMONTH)+"-01 00:00:00");
        Integer currentMonthProduct=productService.selectEntityCount(product);
        Member member=new Member();
        member.setStartDate(DateUtil.DateToStr(newDate,DateUtil.DATE_YEARMONTH)+"-01 00:00:00");
        Integer currentMonth=memberService.selectMemberCount(member);;
        //获取最近7天
        for(int i=0;i<7;i++){
            dataList.add(DateUtil.DateToStr(DateUtil.getDateOfDate(newDate,i),DateUtil.DATE_PATTERN));
            Member memberEntity=new Member();
            memberEntity.setStartDate(dataList.get(i)+" 00:00:00");
            memberEntity.setEndDate(dataList.get(i)+" 23:59:59");
            int  mSize= memberService.selectMemberCount(memberEntity);


            Product productEntity=new Product();
            productEntity.setStartDate(dataList.get(i)+" 00:00:00");
            productEntity.setEndDate(dataList.get(i)+" 23:59:59");

            int  pSize= productService.selectEntityCount(productEntity);

            memberList.add(mSize);
            productList.add(pSize);
        }


        return new ModelAndView("/baseMain")
                .addObject("baseUserInfo",baseUserInfo)
                .addObject("dataList", JSONArray.toJSONString(dataList))
                .addObject("memberList",JSONArray.toJSONString(memberList))
                .addObject("dataList",JSONArray.toJSONString(dataList))
                .addObject("productList",JSONArray.toJSONString(productList))
                .addObject("currentAllMember",currentAllMember)
                .addObject("currentMonthProduct",currentMonthProduct)
                .addObject("currentMonth",currentMonth);
    }

    /**
     * 个人中心页面
     * */
    @RequestMapping(value="/index")
    public ModelAndView Index(HttpServletRequest request,HttpServletResponse response){
        BaseUserInfo baseUserInfo=acceptCurrentUser(request);
        //菜单查询
        BaseMenu baseMenu=new BaseMenu();
        baseMenu.setRemovetag(BaseConstant.REMOVE_N);
        baseMenu.setMenugrade(BaseConstant.MENU_ONE);
        baseMenu.setDepartId(baseUserInfo.getDepartid());
        List<BaseMenu> baseMenuList=baseMenuService.selectEntityByLeft(baseMenu);
        return new ModelAndView("/index").addObject("baseMenuList",baseMenuList).addObject("baseMenu",baseMenuList.get(0)).addObject("baseUserInfo",baseUserInfo);
    }

}
